package com.mj.util;

import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;

public class BitmapUtil {
	/***
	 * 从Assets中读取图片
	 */
	public static Bitmap getImageFromAssetsFile(Context context, String fileName) {
		Bitmap image = null;
		AssetManager am = context.getResources().getAssets();
		try {
			InputStream is = am.open(fileName);
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		return image;
	}

	/***
	 * 给图片添加圆形遮罩层
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getCroppedBitmap(Bitmap bitmap, int width, int height) {
		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff808080;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, width, height);
		// 遮罩层
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawCircle(width / 2, width / 2, width / 2, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, null, rect, paint);
		// 灰边框
		paint.setStrokeWidth(3);
		paint.setStyle(Paint.Style.STROKE);
		canvas.drawCircle(width / 2, width / 2, width / 2, paint);
		// 回收
		bitmap.recycle();
		return output;
	}
}
